﻿using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using Serilog;

namespace ToolApp.EdgeRewards;

public class Activities
{
    public Activities(EdgeRewardsBase sef)
    {
        var originalWindow = sef.WebDriver!.CurrentWindowHandle;
        Log.Information("开始检查限时任务Activities...");
        sef.WebDriver.Navigate().GoToUrl("https://rewards.bing.com/?form=dash_2");
        //document.querySelectorAll('a.ds-card-sec.ng-scope').forEach(function(element) { var childElement = element.querySelector('span.mee-icon.mee-icon-AddMedium'); if (childElement) { element.click(); } });
        foreach (var element in sef.WebDriver.FindElements(By.CssSelector("a.ds-card-sec.ng-scope")))
        {
            if (element.FindElements(By.CssSelector("span.mee-icon.mee-icon-AddMedium")).Count == 0)
            {
                continue;
            }

            Log.Information("任务{0}，+{1}", element.FindElement(By.CssSelector("h3.c-heading.ng-binding")).Text,
                element.FindElement(By.CssSelector("span.c-heading.pointsString.ng-binding.ng-scope")).Text);
            element.Click();
            // 等待新窗口或标签页
            sef.WaitUntil(wd => wd.WindowHandles.Count == 2);
            // 循环执行，直到找到一个新的窗口句柄
            foreach (var window in sef.WebDriver.WindowHandles)
            {
                if (originalWindow == window)
                {
                    continue;
                }

                sef.WebDriver.SwitchTo().Window(window);
                break;
            }

            // 等待新标签页完成加载内容
            sef.WaitUntilUrl(["https://cn.bing.com/"]);
            //关闭标签页或窗口
            sef.WebDriver.Close();
            //切回到之前的标签页或窗口
            sef.WebDriver.SwitchTo().Window(originalWindow);
        }
    }
}